/*
编写 : Hexh
时间 : 2012-7-9 10:48:31
*/
using System;
using System.ComponentModel;
using System.Web;
using System.Web.Mvc;
using FsCarInfo.Core.Entity;
using FsCarInfo.Facade;
using HMIS.FrameWork;
using HMIS.Infrastructure.Core.Entities;
using HMIS.Infrastructure.Facade;
using HMIS.Infrastructure.Facade.Authority;
using HMIS.MVC.CommonSupport;
using HMIS.MVC.ViewModel;
using System.Linq;

namespace HMIS.MVC.Controllers
{
	/// <summary>
	///	 the mvc class of FsGatelog
	/// </summary>
	public class FsGatelogController : BaseController
	{

		private readonly IFsGateinfoFacade FsGateinfoFacade;
		private readonly IFsGatelogFacade FsGatelogFacade;
		private readonly IHospUserFacade HospUserFacade;
		private readonly IInfraIdcardFacade InfraIdcardFacade;
		private readonly IFsGatelogListFacade FsGatelogListFacade;
		private readonly IFsAreaFacade FsAreaFacade;

		public FsGatelogController(IFsGatelogFacade FsGatelogFacade, IHospUserFacade HospUserFacade
			, IInfraIdcardFacade InfraIdcardFacade, IFsGatelogListFacade FsGatelogListFacade
			, IFsGateinfoFacade FsGateinfoFacade, IFsAreaFacade FsAreaFacade)
		{
			this.FsGatelogFacade = FsGatelogFacade;
			this.HospUserFacade = HospUserFacade;
			this.InfraIdcardFacade = InfraIdcardFacade;
			this.FsGatelogListFacade = FsGatelogListFacade;
			this.FsGateinfoFacade = FsGateinfoFacade;
			this.FsAreaFacade = FsAreaFacade;
		}

		[Description("访问道闸出入控制页面")]
		[ViewPage]
		public ActionResult ViewFsGateControl()
		{
			return View();
		}

		[Description("访问道闸出入管理页面")]
		[ViewPage]
		public ActionResult ViewFsGatelogList()
		{
			return View();
		}


		[ExtResult]
		[Description("根据卡号读取ID卡信息")]
		public ActionResult GetLatestLogByIdCard()
		{
			FsGatelog gateLog = FsGatelogFacade.GetCurGateLogByIdCard(Request["CardUid"], Request["CarNo"], Request["GateId"]);
			
			return this.JsonFormat(
			   new ExtFormLoadData<FsGatelog> { success = true, data = new FsGatelog[] { gateLog } },
			   new string[] { "InfraIdcard" }
			   );
		}

		[ExtResult]
		[Description("登记车辆经道闸出入信息")]
		public ActionResult SaveOrUpdate()
		{
			FsGatelog gateLog = FsGatelogFacade.GetCurGateLogByIdCard(Request["CardUid"], Request["CarNo"], Request["GateId"]);
			
			// 判断上送的放行是否合法
			string ioType = Request["IOType"];
			if (gateLog.IoControlFlag.IndexOf(Request["IOType"]) < 0)
			{
				throw new ValidationException("该车辆状态不允许该操作!");
			}

			// 通行明细
			FsGatelogList entity = new FsGatelogList
			{
				LogId = gateLog.Id,
				GateId = Request["GateId"],
				IOType = ioType,
				InAreaId = ioType == "I" ? gateLog.CurrentGate.InAreaId : gateLog.CurrentGate.OutAreaId,
				OutAreaId = ioType == "O" ? gateLog.CurrentGate.InAreaId : gateLog.CurrentGate.OutAreaId,
				CreateUser = System.Web.HttpContext.Current.User.Identity.Name,
				Description = Request["Description"],
				ApprState = "9", //默认无需授权
			};
			FsArea inArea = FsAreaFacade.Get(entity.InAreaId);
			if (inArea.IsAppr)
			{
				entity.ApprState = "0";
			}
			gateLog.GateLogList.Add(entity);

			gateLog.CarNo = Request["CarNo"];
			if (gateLog.EntTime == null)
				gateLog.EntTime = System.DateTime.Now;

			// 临时卡出闸则结束一次记录
			if (gateLog.InfraIdcard.Type == InfraIdcardType.TempGateCard)
			{
				if (inArea.Code == "00000")
				{
					gateLog.LevTime = System.DateTime.Now;
					gateLog.State = "0";
				}
			}
			// 保存信息
			FsGatelogFacade.SaveOrUpdate(gateLog);
			return this.JsonFormat(new ExtResult { success = true, id = gateLog.Id });
		}

		[ExtResult]
		[Description("授权车辆通行")]
		public ActionResult AccessApprove()
		{
			CurrentUser CurrentUser = new CurrentUser();
			if (!String.IsNullOrEmpty(Request["Ids"]))
			{
				string[] Ids = Request["Ids"].Split(',');
				for (int i = 0; i < Ids.Length; i++)
				{
					if (!string.IsNullOrEmpty(Ids[i]))
					{
						FsGatelogList entity;
						entity = FsGatelogListFacade.Get(Ids[i]);
						if (entity.ApprState == "0")
						{
							entity.ApprState = "1";
							entity.ApprTime = System.DateTime.Now;
							entity.ApprUserId = CurrentUser.UserInfo.Id;
							FsGatelogListFacade.SaveOrUpdate(entity);
						}
					}
				}
				return this.JsonFormat(new ExtResult { success = true });
			}
			return this.JsonFormat(new ExtResult { success = false, msg = "无待授权的记录。" });
		}

		

		[ExtResult]
		[Description("重置车辆通信记录")]
		public ActionResult GateLogReWrite()
		{
			FsGatelog gatelog = FsGatelogFacade.GetCurrentLogByIdCard(Request["CardUId"]);
			// 将旧的通行记录置为结束
			if (gatelog != null)
			{
				// 执行下判断。
				if (gatelog.CarNo != Request["CarNo"])
				{
					throw new ValidationException("输入的车牌号与该ID卡待核销的车牌号不一致.");
				}
				if (gatelog.InfraIdcard.Type != (InfraIdcardType)Convert.ToInt32(Request["CardType"]))
				{
					throw new ValidationException("待核销的ID卡类型不一致.");
				}
				// 登记核销信息
				gatelog.State = "9";
				gatelog.LevTime = System.DateTime.Now;
				gatelog.Description = gatelog.Description + " [核销说明]:" + Request["Description"];
				//todo 登记核销人信息
				// 保存记录
				FsGatelogFacade.SaveOrUpdate(gatelog);
			}
			// 创建一个新的通行记录
			InfraIdcard idCard = InfraIdcardFacade.GetByCardUId(Request["CardUId"]);
			if (idCard.Type != (InfraIdcardType)Convert.ToInt32(Request["CardType"]))
			{
				throw new ValidationException("ID卡类型不一致.");
			}
			FsGatelog newLog = new FsGatelog
			{
				CarNo = Request["CarNo"],
				CardUid = idCard.CardUid,
				Type = idCard.Type,
				State = "0",
				EntTime = System.DateTime.Now,
				Description = "[重置说明]:" + Request["Description"],
			};
			FsGatelogFacade.SaveOrUpdate(newLog);

			return this.JsonFormat((new ExtResult { success = true }));
		}

		[ExtResult]
		[Description("批量重置车辆通信记录")]
		public ActionResult ReWrite()
		{
			CurrentUser CurrentUser = new CurrentUser();
			if (!String.IsNullOrEmpty(Request["Ids"]))
			{
				string[] Ids = Request["Ids"].Split(',');
				for (int i = 0; i < Ids.Length; i++)
				{
					if (!string.IsNullOrEmpty(Ids[i]))
					{
						FsGatelogList entity;
						entity = FsGatelogListFacade.Get(Ids[i]);
						FsGatelog gatelog = entity.FsGatelog;
						if (gatelog.State == "0")
						{
							// 登记核销信息
							gatelog.State = "9";
							gatelog.LevTime = System.DateTime.Now;
							FsGatelogFacade.SaveOrUpdate(gatelog);

							FsGatelog newLog = new FsGatelog
							{
								CarNo = gatelog.CarNo,
								CardUid = gatelog.InfraIdcard.CardUid,
								Type = gatelog.InfraIdcard.Type,
								State = "0",
								EntTime = System.DateTime.Now,
							};
							FsGatelogFacade.SaveOrUpdate(newLog);
						}
					}
				}
				return this.JsonFormat(new ExtResult { success = true });
			}
			return this.JsonFormat(new ExtResult { success = false, msg = "无待核销的记录。" });
		}

		[ExtResult]
		[Description("核销车辆通信记录")]
		public ActionResult GateLogWriteOff()
		{
			FsGatelog gatelog = FsGatelogFacade.GetCurrentLogByIdCard(Request["CardUId"]);
			if (gatelog == null)
			{
				throw new ValidationException("该ID卡没有待核销的记录.");
			}
			if (gatelog.CarNo != Request["CarNo"])
			{
				throw new ValidationException("输入的车牌号与该ID卡待核销的车牌号不一致.");
			}
			if (gatelog.InfraIdcard.Type != (InfraIdcardType)Convert.ToInt32(Request["CardType"]))
			{
				throw new ValidationException("待核销的ID卡类型不一致.");
			}
			// 登记核销信息
			gatelog.State = "9";
			gatelog.LevTime = System.DateTime.Now;
			gatelog.Description = gatelog.Description + " [核销说明]:" + Request["Description"];
			//todo 登记核销人信息
			// 保存记录
			FsGatelogFacade.SaveOrUpdate(gatelog);
			return this.JsonFormat((new ExtResult { success = true }));
		}
		
		[ExtResult]
		[Description("批量核销车辆通信记录")]
		public ActionResult WriteOff()
		{
			CurrentUser CurrentUser = new CurrentUser();
			if (!String.IsNullOrEmpty(Request["Ids"]))
			{
				string[] Ids = Request["Ids"].Split(',');
				for (int i = 0; i < Ids.Length; i++)
				{
					if (!string.IsNullOrEmpty(Ids[i]))
					{
						FsGatelogList entity;
						entity = FsGatelogListFacade.Get(Ids[i]);
						FsGatelog gatelog = entity.FsGatelog;
						if (gatelog.State == "0")
						{
							// 登记核销信息
							gatelog.State = "9";
							gatelog.LevTime = System.DateTime.Now;
							FsGatelogFacade.SaveOrUpdate(gatelog);
						}
					}
				}
				return this.JsonFormat(new ExtResult { success = true });
			}
			return this.JsonFormat(new ExtResult { success = false, msg = "无待核销的记录。" });
		}

		[ExtResult]
		[Description("删除FsGatelog基本资料")]
		public ActionResult Delete()
		{
			FsGatelogFacade.Delete(Request["Id"]);
			return this.JsonFormat((new ExtResult { success = true }));
		}

		[ExtResult]
		[Description("物理删除FsGatelog基本资料")]
		public ActionResult PhysicsDelete()
		{
			FsGatelogFacade.PhysicsDelete(Request["Id"]);
			return this.JsonFormat((new ExtResult { success = true }));
		}

		[Description("获取FsGatelog清单")]
		public ActionResult GetPlist()
		{
			long total;
			var data = FsGatelogFacade.GetPlist(
				Request["q_query"],
				int.Parse(Request["start"] == null ? "0" : Request["start"]),
				int.Parse(Request["limit"] == null ? "0" : Request["limit"]),
				Request["sort"],
				Request["dir"],
				this.DesDataFilter(Request["filter"]),
				out total);
			//TODO : 修改关联查询返回的类型
			return this.JsonFormat(
				new ExtGirdData<FsGatelog> { total = total, data = data },
				new string[] { "CustomType" });
		}

		[Description("获取FsGatelog信息")]
		public ActionResult GetById()
		{
			var entity = FsGatelogFacade.Get(Request["Id"]);
			return this.JsonFormat(
			   new ExtFormLoadData<FsGatelog> { data = new FsGatelog[] { entity } }, new string[] { "AuthorizeUsers" }
			   );
		}

		[ExtResult]
		[Description("判断FsGatelog字段是否唯一")]
		public ActionResult IsFieldExist()
		{
			var result = FsGatelogFacade.IsFieldExist(Request["FieldName"], Request[Request["FieldName"]], Request["Id"]);
			return this.JsonFormat(new ExtResult { success = !result, msg = "已存在相同的项!" });
		}
	}
}
